import * as echarts from '../components/ec-canvas/echarts';
var http = require('../../script/order.js');
Component({
  options: {
    addGlobalClass: true,
  },
  /**
   * 组件的属性列表
   */
  properties: {
    key: {
      type: Number,
      value: 0
    },
  },
  observers: {
    'key': function (val) {
      if (val != null && val > 0) {
        this.GetData();
      }
    }
  },
  lifetimes: {
    created: function () {
      this.GetData();
    },
    attached: function () {

    },
    ready: function () {
      this.ecComponent_ordertype = this.selectComponent('#ordertype-chart-dom');
      this.initOrderTypeChart();

      this.ecComponent_OrdertTrend = this.selectComponent('#ordertrend-chart-dom');
      this.initOrderTrendChart();
    },
    detached: function () {
      if (this.chart_ordertype) {
        this.chart_ordertype.dispose();
        this.chart_ordertype = null;
      }
      if (this.chart_OrderTrend) {
        this.chart_OrderTrend.dispose();
        this.chart_OrderTrend = null;
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    /************ 工单完成率 ***********/
    SumInfo: {
      NotHandler: 0,
      NotReceive: 0,
      OrderNum: 0,
      OverTime: 0,
      UrgeNum: 0,
      FinishRate: 0
    },
    /************ 工单完成率 ***********/

    /************ 工单类型分析 ***********/
    ecOrdertype: {
      lazyLoad: true
    },
    noOrderTypData: false,
    OrderTypChartData: [],
    /************ 工单类型分析 ***********/

    /************ 工单完成率 ***********/
    AreaRank: [],
    DeptRank: [],
    StationRank: [],
    orderCompleteData: [],
    rankMode: 0,
    noRankData: false,
    /************ 工单完成率 ***********/

    /************ 工单趋势分析 ***********/
    ecOrderTrend: {
      lazyLoad: true
    },
    orderTrendData: [],
    noOrderTrendData: false,
    /************ 工单趋势分析 ***********/
    color: ['#01e1fb', '#00a8ff', '#3270ff', '#40e1d1', '#ff9900', '#ff6600', '#ff0000'],
  },

  /**
   * 组件的方法列表
   */
  methods: {
    GetData() {
      http.GetOrderTotalData().then(res => {
        if (res.code === 200) {
          const OrderTotal = res.data.OrderTotal;
          let rate = 0;
          if(OrderTotal){
            if(OrderTotal.OrderNum > 0){
              rate = Math.round((OrderTotal.OrderNum - OrderTotal.NotReceive - OrderTotal.NotHandler) * 10000 / OrderTotal.OrderNum) / 100
            }
          }
          this.setData({
            SumInfo: {
              NotHandler: OrderTotal ? OrderTotal.NotHandler : 0,
              NotReceive: OrderTotal ? OrderTotal.NotReceive : 0,
              OrderNum: OrderTotal ? OrderTotal.OrderNum : 0,
              OverTime: OrderTotal ? OrderTotal.OverTime : 0,
              UrgeNum: OrderTotal ? OrderTotal.UrgeNum : 0,
              FinishRate: rate
            },
            AreaRank: res.data.AreaRank || [],
            DeptRank: res.data.DeptRank || [],
            StationRank: res.data.StationRank || [],
            OrderTypes: res.data.OrderTypes,
            orderTrendData: res.data.OrderNumByDate,
            noOrderTrendData: res.data.OrderNumByDate.length === 0
          });
          this.getOrderTypeData();
          this.getRankData();
          this.setOrderTrendChartOption();
        }
      })
    },
    getOrderTypeData() {
      const list = [];
      let noData = false;
      if (this.data.OrderTypes == null) {
        noData = true;
      } else {
        for (let k in this.data.OrderTypes) {
          const val = this.data.OrderTypes[k] ? this.data.OrderTypes[k] : 0
          list.push({
            name: k,
            value: val
          });
        }
        if (list.length === 0) {
          noData = true;
        }
      }
      this.setData({
        noOrderTypData: noData,
        OrderTypChartData: list
      });
      this.setOrderTypeChartOption();
    },
    changeRankMode(e) {
      const mode = parseInt(e.currentTarget.dataset.mode);
      if (this.data.rankMode === mode) return;
      this.setData({
        rankMode: mode
      });
      this.getRankData();
    },
    getRankData() {
      const mode = this.data.rankMode;
      let rankData = [];
      if (mode === 0) {
        rankData = [...this.data.AreaRank];
      } else if (mode === 1) {
        rankData = [...this.data.StationRank];
      } else if (mode === 2) {
        rankData = [...this.data.DeptRank];
      }
      this.setData({
        orderCompleteData: rankData,
        noRankData: rankData.length === 0
      });
    },
    initOrderTypeChart() {
      this.ecComponent_ordertype.init((canvas, width, height, dpr) => {
        // 获取组件的 canvas、width、height 后的回调函数
        // 在这里初始化图表
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
        this.chart_ordertype = chart;
        this.setOrderTypeChartOption();
        // 注意这里一定要返回 chart 实例，否则会影响事件处理等
        return chart;
      });
    },
    setOrderTypeChartOption() {
      if (!this.chart_ordertype) return;
      if (this.data.OrderTypChartData.length === 0) return;

      const data = [...this.data.OrderTypChartData];
      data.sort((a, b) => b.value - a.value);
      const option = {
        color: [
          "#FAE927",
          "#E9E416",
          "#C9DA36",
          "#9ECB3C",
          "#6DBC49",
          "#37B44E",
          "#3DBA78",
          "#14ADCF",
          "#209AC9",
          "#1E91CA",
          "#2C6BA0",
          "#2B55A1",
          "#2D3D8E",
          "#44388E",
          "#6A368B",
          "#7D3990",
          "#A63F98",
          "#C31C88",
          "#D52178",
          "#D5225B",
          "#D02C2A",
          "#D44C2D",
          "#F57A34",
          "#FA8F2F",
          "#D99D21",
          "#CF7B25",
          "#CF7B25",
          "#CF7B25",
        ],
        legend: {
          orient: "vertical",
          left: "0",
          top: "middle",
          itemWidth: 20,
          itemHeight: 15,
          textStyle: {
            color: "#606266",
            fontSize: 13,
          },
          formatter: (name) => {
            const item = data.find(i => i.name === name);
            return name + ' ' + item.value;
          }
        },
        calculable: true,
        tooltip: {
          trigger: 'item',
          valueFormatter: function (val) {
            return val + " 单";
          },
          textStyle: {
            color: "#313131",
            fontSize: 13,
          },
          confine: true,
        },
        series: [{
            name: "工单类型",
            type: "pie",
            startAngle: 0,
            clockwise: false,
            radius: ["20%", "80%"],
            center: ["65%", "50%"],
            roseType: "area",
            avoidLabelOverlap: false,
            padAngle: 3,
            label: {
              show: true,
              position: "inside",
              formatter: "{c}",
              textStyle: {
                color: "#fff",
                fontSize: 13,
              },
            },
            itemStyle: {
              borderRadius: 6,
            },
            data: data,
          },
          {
            type: "pie",
            radius: '12%',
            data: [100],
            center: ["65%", "50%"],
            itemStyle: {
              color: "#E83A30",
            },
            hoverAnimation: false,
            label: {
              show: false,
            },
            tooltip: {
              show: false
            },
          },
        ],
      };
      this.chart_ordertype.setOption(option);
    },
    initOrderTrendChart: function () {
      this.ecComponent_OrdertTrend.init((canvas, width, height, dpr) => {
        // 获取组件的 canvas、width、height 后的回调函数
        // 在这里初始化图表
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
        this.chart_OrderTrend = chart;
        this.setOrderTrendChartOption();
        // 注意这里一定要返回 chart 实例，否则会影响事件处理等
        return chart;
      });
    },
    setOrderTrendChartOption() {
      if (!this.chart_OrderTrend) return;
      if (this.data.orderTrendData.length === 0) return;
      const resData = [...this.data.orderTrendData];
      let xData = [];
      let yData1 = [];
      let yData2 = [];
      for (let i = resData.length - 1; i >= 0; i--) {
        const item = resData[i];
        xData.push(item.OrderDate);
        yData1.push(item.OrderNum);
        yData2.push(item.CompleteNum);
      }
      const option = {
        tooltip: {
          trigger: 'axis',
          textStyle: {
            textShadowBlur: 0,
          },
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          },
          // renderMode: 'richText',
          valueFormatter: function (val) {
            return val + " 单";
          },
        },
        legend: {

        },
        grid: {
          top: '50',
          right: '40',
          left: '10',
          bottom: '30',
          containLabel: true,
        },
        xAxis: [{
          type: 'category',
          // boundaryGap: false,
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {
            formatter: (val) => {
              return val.slice(6)
            }
          },
          data: xData,
          axisPointer: {
            type: 'shadow'
          }
        }],
        yAxis: [{
          type: 'value',
          name: '数量（单）',
          axisLine: {
            show: true,
          },
          axisLabel: {

          }
        }],
        series: [{
            name: '工单总数',
            type: 'bar',
            data: yData1,
            barMaxWidth: 10,
            markPoint: {
              data: [{
                  type: 'max',
                  name: 'Max'
                },
                {
                  type: 'min',
                  name: 'Min'
                }
              ]
            },
            markLine: {
              data: [{
                type: 'average',
                name: 'Avg'
              }]
            }
          },
          {
            name: '完成数',
            type: 'bar',
            data: yData2,
            barMaxWidth: 10,
            markPoint: {
              data: [{
                  type: 'max',
                  name: 'Max'
                },
                {
                  type: 'min',
                  name: 'Min'
                }
              ]
            },
            markLine: {
              data: [{
                type: 'average',
                name: 'Avg'
              }]
            }
          }
        ]
      }
      this.chart_OrderTrend.setOption(option);
    },
  }
})